package edu.zut.hb.bailan0.producter;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.TimeoutException;

public class Producer extends Thread{
    private Socket clientSocket;

    public Producer(Socket clientSocket) {
        this.clientSocket = clientSocket;
    }
//
    public void run(){
        try{
            //1 创建一个ConnectionFactory, 并进行配置
            //2 通过连接工厂创建连接
            Connection connection = ConnectionUtils.getConnection();
            Channel channel = connection.createChannel();
            //创建交换机
            String exchangeName = "test_fanout";
            channel.exchangeDeclare(exchangeName, BuiltinExchangeType.FANOUT, true, false, false, null);
            //创建队列 2个
            String queue1 = "test_fanout_queue1";
            String queue2 = "test_fanout_queue2";
            channel.queueDeclare(queue1, true, false, false, null);
            channel.queueDeclare(queue2, true, false, false, null);
            //绑定队列和交换机
            channel.queueBind(queue1, exchangeName, "");
            channel.queueBind(queue2, exchangeName, "");
            boolean flag=true;
            while(flag)
            {
                Scanner scanner=new Scanner(System.in);
                String body =scanner.next();
                //发送消息
                channel.basicPublish(exchangeName, "", null, body.getBytes());
            }

            //释放资源
            channel.close();
            connection.close();
        }catch (IOException e) {
            e.printStackTrace();
        }catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
